<?php
/**
 * Description: 描述
 * Created by PhpStorm.
 * User: congyukun
 * Date: 2021/5/10
 * Time: 15:17
 */

namespace Biz\service\wiki;


use Biz\cache\advertisement\CNewUserProfile;
use Biz\model\brand\Brand;
use Biz\service\Store\StoreBasicService;
use Biz\tools\helper\Common;
use Doraemon\model\Es\WikiBasic as EsWikiBasic;
use Doraemon\tools\Log;

class FindWIkiService
{
    const FIND_WIKI_CLASSIFY = [
        0 => [
            'name' => '每日精选',
            'classify' => [
            ]
        ],
        1 => [
            'name' => '小众家饰',
            'classify' => [
                ['id' => 682, 'name' => '装饰摆件'],
                ['id' => 658, 'name' => '地毯地垫'],
                ['id' => 655, 'name' => '抱枕坐垫'],
            ],
            'goods_tags' => [
                ['tag' => '地毯地垫', 'deep' => 3],
                ['tag' => '帘子', 'deep' => 3],
                ['tag' => '装饰字画', 'deep' => 3],
                ['tag' => '布艺家纺', 'deep' => 2],
                ['tag' => '花艺', 'deep' => 3],
                ['tag' => '镜子', 'deep' => 3],
                ['tag' => '抱枕坐垫', 'deep' => 3],
                ['tag' => '桌面装饰', 'deep' => 3],
                ['tag' => '钟表', 'deep' => 3],
                ['tag' => '墙饰', 'deep' => 3],
                ['tag' => '香薰蜡烛', 'deep' => 3],
                ['tag' => '工艺品', 'deep' => 3],
                ['tag' => '沙发罩', 'deep' => 3],
                ['tag' => '冰箱贴', 'deep' => 3],
            ]
        ],
        2 => [
            'name' => '颜值餐厨',
            'classify' => [
                ['id' => 1949, 'name' => '餐厨用品'],
                ['id' => 1209, 'name' => '餐厨布艺'],
            ],
            'goods_tags' => [
                ['tag' => '餐厨用品', 'deep' => 2],
            ]
        ],
        3 => [
            'name' => '清洁好物',
            'classify' => [
                ['id' => 1083, 'name' => '清洁工具'],
                ['id' => 1082, 'name' => '清洁剂'],
            ],
            'goods_tags' => [
                ['tag' => '清洁用品', 'deep' => 2],
            ]
        ],
        4 => [
            'name' => '收纳神器',
            'classify' => [
                ['id' => 622, 'name' => '厨房收纳'],
                ['id' => 623, 'name' => '浴室收纳'],
                ['id' => 1583, 'name' => '墙面收纳'],
                ['id' => 1594, 'name' => '其他收纳'],
            ],
            'goods_tags' => [
                ['tag' => '收纳工具', 'deep' => 2],
                ['tag' => '日用小件', 'deep' => 2],
            ]
        ],
        5 => [
            'name' => '风格家居',
            'classify' => [
                ['id' => 823, 'name' => '家具'],
                ['id' => 810, 'name' => '灯具灯饰'],
            ],
            'goods_tags' => [
                ['tag' => '柜', 'deep' => 2],
                ['tag' => '沙发', 'deep' => 2],
                ['tag' => '桌', 'deep' => 2],
                ['tag' => '架', 'deep' => 2],
                ['tag' => '几', 'deep' => 2],
                ['tag' => '床', 'deep' => 2],
                ['tag' => '椅', 'deep' => 2],
                ['tag' => '吊灯', 'deep' => 3],
                ['tag' => '凳', 'deep' => 2],
                ['tag' => '台灯', 'deep' => 3],
                ['tag' => '射灯筒灯', 'deep' => 3],
                ['tag' => '落地灯', 'deep' => 3],
                ['tag' => '灯具配件', 'deep' => 3],
                ['tag' => '壁灯', 'deep' => 3],
                ['tag' => '吸顶灯', 'deep' => 3],
                ['tag' => '家具配件', 'deep' => 2],
                ['tag' => '屏风', 'deep' => 2],
                ['tag' => '吧台椅', 'deep' => 3],
            ]
        ],
        6 => [
            'name' => '品质家电',
            'classify' => [
                ['id' => 532, 'name' => '厨房小电'],
                ['id' => 536, 'name' => '生活家电'],
                ['id' => 531, 'name' => '清洁电器'],
            ],
            'goods_tags' => [
                ['tag' => '影音产品', 'deep' => 3],
                ['tag' => '厨卫小电', 'deep' => 3],
                ['tag' => '清洁电器', 'deep' => 3],
                ['tag' => '日用电器', 'deep' => 3],
            ]
        ],
    ];

    public static function getUserClassifyList($uid)
    {
        $list[] = [
            'classify_id' => 0,
            'classify_name' => '每日精选'
        ];
        $today = date('Ymd');
        if ($today < 20220209) {
            $list[] = [
                'classify_id' => 220118,
                'classify_name' => '🏮年味气氛组'
            ];
            $list[] = [
                'classify_id' => 220119,
                'classify_name' => '📺添个大件'
            ];
            $list[] = [
                'classify_id' => 220120,
                'classify_name' => '🔮精致年礼'
            ];
        }
        if ($uid) {
            $tags = CNewUserProfile::getOneWithField($uid, ['action_interest_tag_goods']);
            $tags = $tags['action_interest_tag_goods'] ?? '';
            $tags = $tags ? explode(',', $tags) : [];
        } else {
            $tags = [];
        }
        $map = FindWIkiService::FIND_WIKI_CLASSIFY;
        unset($map[0]);
        $sortList = self::sortClassify($map, $tags);
        $list = array_merge($list, $sortList);
        return $list;
    }

    private static function sortClassify($map, $tags = [])
    {
        $result = [];
        foreach ($map as $key => $row) {
            $score = 0;
            $count = 0;
            if ($row['goods_tags']) {
                foreach ($row['goods_tags'] as $item) {
                    if ($tags && in_array($item['tag'], $tags)) {
                        $count += 1;
                        $avg = $item['deep'] == 3 ? 2 : 1;
                        $score += $avg;
                    }
                }
            }
            $result[] = [
                'classify_id' => (int)$key,
                'classify_name' => $row['name'],
                'score' => $score,
                'count' => $count,
            ];
        }
        if ($tags) {
            $sortScoreArr = array_column($result, 'score');
            $sortCountArr = array_column($result, 'count');
            $sortIdArr = array_column($result, 'classify_id');
            array_multisort($sortScoreArr, SORT_DESC, SORT_NUMERIC, $sortCountArr, SORT_ASC, SORT_NUMERIC, $sortIdArr, SORT_ASC, SORT_NUMERIC, $result);
        }
        $list = [];
        foreach ($result as $row) {
            $list[] = [
                'classify_id' => (int)$row['classify_id'],
                'classify_name' => $row['classify_name'],
                //'score' => $row['score'],//debug
                //'count' => $row['count'],//debug
            ];
        }
        return $list;
    }


    /**
     * 根据分类 获取按照热度排序的wiki合集
     * @param $classifyId
     * @param $page
     * @param int $per_page
     * @param int $wiki_id 过滤当前wiki_id
     * @return array|mixed
     */
    public static function getWikiIdsByClassifyId($classifyId, $page, int $per_page = 10, int $wiki_id = 0)
    {
        $redis = new \Hhz\Redis\newCache(\hhz\constant\redis\redisKeys::KEY_B_CACHE_CATEGORY_CLASSIFY_);
        $cate_ids = $redis->getCache($classifyId);
        Log::debug('getWikiIdsByClassifyId', ['classify_id' => $classifyId, 'cate_ids' => $cate_ids]);
        $cate_ids = $cate_ids ? explode(',', $cate_ids) : [];

        //偏移量，当前页-1乘以每页显示条数
        $start = ($page - 1) * $per_page;
        //取所有wiki 根据热多排序
        return $cate_ids ? EsWikiBasic::searchGetCategoryWikiId($cate_ids, $start, $per_page, $wiki_id) : [];
    }

    /**
     * 通过分类id 获取 wiki_id合集总数
     * @param $classifyId
     * @param int $wiki_id
     * @return array|int|mixed
     */
    public static function getCategoryWikiIdCount($classifyId, int $wiki_id = 0)
    {
//        $cate_ids = CategoryClassify::getCategoryRelation($classifyId) ?: '';
        $redis = new \Hhz\Redis\newCache(\hhz\constant\redis\redisKeys::KEY_B_CACHE_CATEGORY_CLASSIFY_);
        $cate_ids = $redis->getCache($classifyId);
        $cate_ids = $cate_ids ? explode(',', $cate_ids) : [];
        //取所有wiki 根据热多排序
        return $cate_ids ? EsWikiBasic::GetCategoryWikiIdCount($cate_ids, $wiki_id) : [];
    }

    /**
     * 获取住友说
     * @param array $wiki_ids
     * @return array
     */
    public static function getTalkAboutNum(array $wiki_ids): array
    {

        $where['wiki_id'] = $wiki_ids;
        $where['status'] = \Biz\model\wiki\ObjRelateWiki::STATUS_NORMAL;
        $obj_wiki_list = \Biz\model\wiki\ObjRelateWiki::getByWhere($where, ['obj_id', 'wiki_id', 'uid']);
        $uids = array_column($obj_wiki_list, 'uid');
        $uids = $uids ? array_filter(array_unique($uids)) : [];
        if (!$uids) {
            return [];
        }
        //品牌uids
        $brandUids = Brand::getUidsByUids($uids);
        $brand_obj_wiki_list = [];
        if ($brandUids) {
            //获取全部住友说
            $brand_where['uid'] = $brandUids;
            $brand_where['status'] = \Biz\model\wiki\ObjRelateWiki::STATUS_NORMAL;
            $brand_where['wiki_id'] = $wiki_ids;
            $brand_obj_wiki_list = \Biz\model\wiki\ObjRelateWiki::getByWhere($brand_where, ['obj_id', 'uid']) ?: [];
            $brand_obj_wiki_list = $brand_obj_wiki_list ? Common::keyBy($brand_obj_wiki_list, 'uid') : [];
        }

        //门店uids
        $storeUids = StoreBasicService::getFieldByWhere(['uid' => $uids], 'uid');
        $store_obj_wiki_list = [];
        if ($storeUids) {
            //获取全部门店说
            $store_where['uid'] = $storeUids;
            $store_where['status'] = \Biz\model\wiki\ObjRelateWiki::STATUS_NORMAL;
            $store_where['wiki_id'] = $wiki_ids;
            $store_obj_wiki_list = \Biz\model\wiki\ObjRelateWiki::getByWhere($store_where, ['obj_id', 'uid']) ?: [];
            $store_obj_wiki_list = $store_obj_wiki_list ? Common::keyBy($store_obj_wiki_list, 'uid') : [];
        }


        //普通uids
        $normalUids = array_diff($uids, $brandUids);
//        $brandList = [];
        $normalList = [];
//        $storeList = [];
        $data = [];
        foreach ($obj_wiki_list as $item) {
            //品牌说内容
            if (in_array($item['uid'], $brandUids)) {
//                if (!in_array($item['obj_id'], $brandList[$item['wiki_id']] ?? [])) {
//                    $brandList[$item['wiki_id']][] = $item['obj_id'];
                $data[$item['wiki_id']]['brand_talk_about_num'] = count($brand_obj_wiki_list[$item['uid']] ?? []);
//                }
            } else if (in_array($item['uid'], $normalUids)) {
                if (!in_array($item['obj_id'], $normalList[$item['wiki_id']] ?? [])) {
                    $normalList[$item['wiki_id']][] = $item['obj_id'];
                    $data[$item['wiki_id']]['talk_about_num'] += 1;
                }
            } else if (in_array($item['uid'], $storeUids)) {
//                if (!in_array($item['obj_id'], $storeList[$item['wiki_id']] ?? [])) {
//                    $storeList[$item['wiki_id']][] = $item['obj_id'];
                $data[$item['wiki_id']]['store_talk_about_num'] = count($store_obj_wiki_list[$item['uid']] ?? []);
//                }
            }
        }
        return $data ?? [];

    }

}